import { Request, Response } from "express";
import { NextFunction } from "express-serve-static-core";
const express = require("express");
const router = express.Router();
import r from "../r";
import * as config from "../../config";
import big from "../../big";

router.get(
  "/selectAssets",
  async (req: Request, res: Response, next: NextFunction) => {
    const { uid, search, hideSmall } = req.query;
    if (process.env.NODE_ENV === "eh") {
      const data = [
        {
          coin: "BTC",
          amount: "0.00002552",
          ava: "0.00000000",
          frozen: "0.00002551",
          id: "abc",
          cid: "sdlkfjkldsf",
          label: "BTC"
        },
        {
          coin: "BTC",
          amount: "0.00002552",
          ava: "0.00002551",
          frozen: "0.00002551",
          id: "abc",
          cid: "sdlkfjkldsf",
          label: "BTC"
        },
        {
          coin: "BTC",
          amount: "0.00002552",
          ava: "0.00002551",
          frozen: "0.00002551",
          id: "abc",
          cid: "sdlkfjkldsf",
          label: "BTC"
        },
        {
          coin: "BTC",
          amount: "0.00002552",
          ava: "0.00002552",
          frozen: "0.00002551",
          id: "abc",
          cid: "sdlkfjkldsf",
          label: "BTC"
        },
        {
          coin: "BTC",
          amount: "0.00002552",
          ava: "0.00002551",
          frozen: "0.00002551",
          id: "abc",
          cid: "sdlkfjkldsf",
          label: "BTC"
        },
        {
          coin: "BTC",
          amount: "0.00002552",
          ava: "0.00002551",
          frozen: "0.00002551",
          id: "abc",
          cid: "sdlkfjkldsf",
          label: "BTC"
        },
        {
          coin: "BTC",
          amount: "0.00002552",
          ava: "0.00002552",
          frozen: "0.00002551",
          id: "abc",
          cid: "sdlkfjkldsf",
          label: "BTC"
        },
        {
          coin: "BTC",
          amount: "0.00002552",
          ava: "0.00002551",
          frozen: "0.00002551",
          id: "abc",
          cid: "sdlkfjkldsf",
          label: "BTC"
        },
        {
          coin: "BTC",
          amount: "0.00002552",
          ava: "0.00002551",
          frozen: "0.00002551",
          id: "abc",
          cid: "sdlkfjkldsf",
          label: "BTC"
        }
      ]
        .filter(d => {
          return (
            d.coin.toLowerCase().indexOf(req.query.search.toLowerCase()) > -1
          );
        })
        .filter(d => {
          if (req.query.hideSmall === "true") {
            return Number(d.ava) > 0;
          }
          return true;
        });
      res.json({
        code: 200,
        data,
        msg: "success"
      });
    }
    try {
      const { zi, mu } = req.query;

      const newurl = `${config.api}/account`;

      const ret = await r(
        {
          method: "GET",
          url: newurl
        },
        req,
        res
      );

      const jsonRet = JSON.parse(ret.body);

      if (jsonRet && jsonRet.data) {
        jsonRet.data = jsonRet.data
          .slice()
          .map((d: any) => {
            return {
              coin: d.coinName,
              ava: d.available,
              id: d.id,
              cid: d.coinId,
              frozen: d.freezed,
              label: d.coinName,
              status: d.state,
              amount: Number(d.freezed) + Number(d.available)
            };
          })
          .filter((d: any) => {
            if (!!req.query.search) {
              return (
                d.coin.toLowerCase().indexOf(req.query.search.toLowerCase()) >
                -1
              );
            }
            return true;
          })
          .filter((d: any) => {
            if (req.query.hideSmall === "true") {
              return Number(d.ava) > 0;
            }
            return true;
          });
      } else {
        jsonRet.data = [];
      }

      res.json(jsonRet);
    } catch (e) {
      res.json({
        code: -1,
        data: undefined,
        msg: e
      });
    }
  }
);

router.get(
  "/findAssetsToBtc",
  async (req: Request, res: Response, next: NextFunction) => {
    const { uid, search, hideSmall } = req.query;
    if (process.env.NODE_ENV === "eh") {
      res.json({
        code: 200,
        data: {
          ava: "0",
          frozen: "0"
        },
        msg: "success"
      });
    }
    try {
      const { zi, mu } = req.query;

      const newurl = `${config.api}/account/getBTC`;

      const ret = await r(
        {
          method: "GET",
          url: newurl
        },
        req,
        res
      );

      const jsonRet = JSON.parse(ret.body);

      if (jsonRet && jsonRet.data) {
        jsonRet.data = {
          ava: jsonRet.data.available,
          frozen: jsonRet.data.freezon,
          total: big.plus(jsonRet.data.available, jsonRet.data.freezon)
        };
      } else {
        jsonRet.data = {
          ava: "0",
          frozen: "0",
          total: "0"
        };
      }

      res.json(jsonRet);
    } catch (e) {
      res.json({
        code: -1,
        data: undefined,
        msg: e
      });
    }
  }
);

router.get(
  "/findDepositAddress",
  async (req: Request, res: Response, next: NextFunction) => {
    const { coin } = req.query;
    if (process.env.NODE_ENV === "eh") {
      const data = "dslkfjlskdjfsfd";
      res.json({
        code: 200,
        data,
        msg: "success"
      });
    }
    const [num2symbol, symbol2num] = await config.selectSymbolConfig();
    try {
      const newurl = `${config.api}/account/depositAddress/${coin}`;

      const ret = await r(
        {
          method: "GET",
          url: newurl
        },
        req,
        res
      );

      const jsonRet = JSON.parse(ret.body);

      res.json(jsonRet);
    } catch (e) {
      res.json({
        code: -1,
        data: undefined,
        msg: e
      });
    }
  }
);

router.get("/findAssets", async function(
  req: Request,
  res: Response,
  next: NextFunction
) {
  const { coin, uid } = req.query;
  if (process.env.NODE_ENV === "eh") {
    res.json({
      code: 200,
      data: {
        coin,
        total: "0.00002551",
        ava: "0.00002551",
        point: 5,
        frozen: "0.00000000",
        feeRatio: "0",
        baseFee: "0.001",
        withdraw: {
          addressLists: [
            {
              coin,
              remark: "sdkljflskfs",
              address: "sldkjflksjflksjdf"
            },
            {
              coin,
              remark: "sdfsaf",
              address: "23423423"
            }
          ],
          min: "0.00011",
          max: "0.1"
        },
        deposit: {
          min: "0",
          confirm: "0"
        }
      },
      msg: "success"
    });
  }
  try {
    const { zi, mu } = req.query;

    const newurl = `${config.api}/account`;

    const ret = await r(
      {
        method: "GET",
        url: newurl
      },
      req,
      res
    );

    const jsonRetWithdrawAddress = await selectWithdrawAddress(coin, req, res);

    const depositConfig: any = {
      BTC: {
        min: "0.001",
        confirm: "2"
      },
      ETH: {
        min: "0.01",
        confirm: "15"
      },
      LSK: {
        min: "1",
        confirm: "310"
      }
    };

    const withdrawConfig: any = {
      BTC: {
        min: "0.01",
        max: "0.02"
      },
      ETH: {
        min: "0.1",
        max: "0.2"
      },
      LSK: {
        min: "1",
        max: "10"
      }
    };

    const jsonRet = JSON.parse(ret.body);
    if (jsonRet && jsonRet.data) {
      jsonRet.data = jsonRet.data
        .slice()
        .map((d: any) => {
          return {
            coin: d.coinName,
            ava: d.available,
            id: d.id,
            cid: d.coinId,
            frozen: d.freezed,
            label: d.coinName,
            status: d.state,
            total: Number(d.freezed) + Number(d.available),
            feeRatio: "0.3",
            baseFee: "0",
            withdraw: {
              addressLists: jsonRetWithdrawAddress.data,
              // doing
              min: withdrawConfig[d.coinName].min,
              max: withdrawConfig[d.coinName].max
            },
            // doing
            deposit: {
              ...depositConfig[d.coinName]
            }
          };
        })
        .filter((d: any) => {
          if (!!coin) {
            return d.coin.toLowerCase().indexOf(coin.toLowerCase()) > -1;
          }
          return true;
        });
    } else {
      jsonRet.data = [];
    }

    if (!!jsonRet.data) {
      jsonRet.data = jsonRet.data[0];
    } else {
      jsonRet.data = undefined;
    }

    res.json(jsonRet);
  } catch (e) {
    res.json({
      code: -1,
      data: undefined,
      msg: e
    });
  }
});

router.get("/selectActiveHistory", function(
  req: Request,
  res: Response,
  next: NextFunction
) {
  res.json({
    code: 200,
    data: [
      {
        coin: "BTC",
        amount: "0.00002552",
        address: "MHGtdHNwSaQzWaK2N7hxxGmELcZnuRK6fj",
        txid:
          "c59bc457c8ec14ed8aa09a4c27915256c96e19e17eb0299677112665a2cc7768",
        ago: 1542858853,
        now: 1542860302,
        status: "1",
        remark: "sdlkfjlksdfsd",
        id: "abc"
      },
      {
        coin: "BTC",
        amount: "0.00002552",
        address: "MHGtdHNwSaQzWaK2N7hxxGmELcZnuRK6fj",
        txid:
          "c59bc457c8ec14ed8aa09a4c27915256c96e19e17eb0299677112665a2cc7768",
        ago: 1542858853,
        now: 1542860302,
        status: "1",
        remark: "sdlkfjlksdfsd",
        id: "abc"
      },
      {
        coin: "BTC",
        amount: "0.00002552",
        address: "MHGtdHNwSaQzWaK2N7hxxGmELcZnuRK6fj",
        txid:
          "c59bc457c8ec14ed8aa09a4c27915256c96e19e17eb0299677112665a2cc7768",
        ago: 1542858853,
        now: 1542860302,
        status: "1",
        remark: "sdlkfjlksdfsd",
        id: "abc"
      }
    ],
    msg: "success"
  });
});

router.get("/selectAddress", function(
  req: Request,
  res: Response,
  next: NextFunction
) {
  res.json({
    code: 200,
    data: [
      {
        coin: "BTC",
        address: "MHGtdHNwSaQzWaK2N7hxxGmELcZnuRK6fj",
        remark: "sdlkfjlksdfsd",
        id: "abc"
      },
      {
        coin: "BTC",
        address: "MHGtdHNwSaQzWaK2N7hxxGmELcZnuRK6fj",
        remark: "sdlkfjlksdfsd",
        id: "abc"
      },
      {
        coin: "BTC",
        address: "MHGtdHNwSaQzWaK2N7hxxGmELcZnuRK6fj",
        remark: "sdlkfjlksdfsd",
        id: "abc"
      }
    ],
    msg: "success"
  });
});

router.get(
  "/selectCoinConfig",
  async (req: Request, res: Response, next: NextFunction) => {
    res.json({
      code: 200,
      data: [
        {
          id: "82",
          coin: "BTC",
          depositAddress: "dslkfjdskljflksjlkfs"
        },
        {
          id: "81",
          coin: "TVC",
          depositAddress: "dslkfjdskljflksjlkfs"
        },
        {
          id: "80",
          coin: "ABBC",
          depositAddress: "dslkfjdskljflksjlkfs"
        }
      ],
      msg: "success"
    });
  }
);

router.get(
  "/coinAddress",
  async (req: Request, res: Response, next: NextFunction) => {
    const { coin } = req.query;
  }
);

router.get(
  "/selectDepositHistory",
  async (req: Request, res: Response, next: NextFunction) => {
    const { search, coin } = req.query;

    try {
      const [num2symbol, symbol2num] = await config.selectSymbolConfig();

      const newurl = `${
        config.api
      }/deposit/history/${coin}?pageNum=1&pageSize=10000000`;

      const ret = await r(
        {
          method: "GET",
          url: newurl
        },
        req,
        res
      );

      const jsonRet = JSON.parse(ret.body);
      const now = Number(Number(new Date().getTime() / 1000).toFixed(0));
      jsonRet.data.list = jsonRet.data.list.slice().map((d: any) => {
        return {
          coin: num2symbol[d.coinId],
          amount: d.amount,
          address: d.address,
          txid: d.txid,
          ago: Number(Number(d.createtime / 1000).toFixed(0)),
          now,
          status: String(d.state),
          id: d.id
        };
      });

      jsonRet.data = jsonRet.data.list;

      res.json(jsonRet);
    } catch (e) {
      res.json({
        code: -1,
        data: undefined,
        msg: e
      });
    }
    // const data = [
    //   {
    //     coin: "BTC",
    //     amount: "0.00002552",
    //     address: "MHGtdHNwSaQzWaK2N7hxxGmELcZnuRK6fj",
    //     txid:
    //       "c59bc457c8ec14ed8aa09a4c27915256c96e19e17eb0299677112665a2cc7768",
    //     ago: 1542858853,
    //     now: 1542860302,
    //     status: "1",
    //     id: "abc"
    //   },
    //   {
    //     coin: "BTC",
    //     amount: "0.00002552",
    //     address: "MHGtdHNwSaQzWaK2N7hxxGmELcZnuRK6fj",
    //     txid:
    //       "c59bc457c8ec14ed8aa09a4c27915256c96e19e17eb0299677112665a2cc7768",
    //     ago: 1542858853,
    //     now: 1542860302,
    //     status: "1",
    //     id: "abc"
    //   },
    //   {
    //     coin: "BTC",
    //     amount: "0.00002552",
    //     address: "MHGtdHNwSaQzWaK2N7hxxGmELcZnuRK6fj",
    //     txid:
    //       "c59bc457c8ec14ed8aa09a4c27915256c96e19e17eb0299677112665a2cc7768",
    //     ago: 1542858853,
    //     now: 1542860302,
    //     status: "1",
    //     id: "abc"
    //   }
    // ].filter(d => {
    //   return d.coin.toLowerCase().indexOf(search.toLowerCase()) > -1;
    // });
    // res.json({
    //   code: 200,
    //   data,
    //   msg: "success"
    // });
  }
);

router.get(
  "/selectWithdrawHistory",
  async (req: Request, res: Response, next: NextFunction) => {
    const { search, coin } = req.query;

    try {
      const [num2symbol, symbol2num] = await config.selectSymbolConfig();

      const newurl = `${
        config.api
      }/withdraw/history/${coin}?pageNum=1&pageSize=10000000`;

      const ret = await r(
        {
          method: "GET",
          url: newurl
        },
        req,
        res
      );

      const jsonRet = JSON.parse(ret.body);

      const now = Number(Number(new Date().getTime() / 1000).toFixed(0));

      jsonRet.data.list = jsonRet.data.list
        .slice()
        .map((d: any) => {
          return {
            coin: coin,
            amount: d.amount,
            address: d.address,
            // doing
            txid: "",
            ago: Number(Number(d.createtime / 1000).toFixed(0)),
            now,
            status: String(d.state),
            id: d.id
          };
        })
        .sort((pre: any, next: any) => {
          return next.ago - pre.ago;
        });
      jsonRet.data = jsonRet.data.list;

      res.json(jsonRet);
    } catch (e) {
      res.json({
        code: -1,
        data: undefined,
        msg: e
      });
    }
    // const data = [
    //   {
    //     coin: "BTC",
    //     amount: "0.00002552",
    //     address: "MHGtdHNwSaQzWaK2N7hxxGmELcZnuRK6fj",
    //     txid:
    //       "c59bc457c8ec14ed8aa09a4c27915256c96e19e17eb0299677112665a2cc7768",
    //     ago: 1542858853,
    //     now: 1542860302,
    //     status: "1",
    //     id: "abc"
    //   },
    //   {
    //     coin: "BTC",
    //     amount: "0.00002552",
    //     address: "MHGtdHNwSaQzWaK2N7hxxGmELcZnuRK6fj",
    //     txid:
    //       "c59bc457c8ec14ed8aa09a4c27915256c96e19e17eb0299677112665a2cc7768",
    //     ago: 1542858853,
    //     now: 1542860302,
    //     status: "1",
    //     id: "abc"
    //   },
    //   {
    //     coin: "BTC",
    //     amount: "0.00002552",
    //     address: "MHGtdHNwSaQzWaK2N7hxxGmELcZnuRK6fj",
    //     txid:
    //       "c59bc457c8ec14ed8aa09a4c27915256c96e19e17eb0299677112665a2cc7768",
    //     ago: 1542858853,
    //     now: 1542860302,
    //     status: "1",
    //     id: "abc"
    //   }
    // ].filter(d => {
    //   return d.coin.toLowerCase().indexOf(search.toLowerCase()) > -1;
    // });
    // res.json({
    //   code: 200,
    //   data,
    //   msg: "success"
    // });
  }
);

async function selectWithdrawAddress(coin: string, req: any, res: any) {
  const [num2symbol, symbol2num] = await config.selectSymbolConfig();

  const newurl = `${
    config.api
  }/withdraw/withdrawAddress/${coin}?pageNum=1&pageSize=1000000`;

  const ret = await r(
    {
      method: "GET",
      url: newurl
    },
    req,
    res
  );

  const jsonRet = JSON.parse(ret.body);

  jsonRet.data = jsonRet.data.list.slice().map((d: any) => {
    return {
      coin: num2symbol[d.coinId],
      remark: d.remark,
      address: d.address,
      id: d.id
    };
  });

  return jsonRet;
}

async function selectWithdrawAddressMap(coin: string, req: any, res: any) {
  const jsonRet = await selectWithdrawAddress(coin, req, res);

  const ret: any = {};

  for (const item of jsonRet.data) {
    ret[item.address] = item;
  }

  return ret;
}

router.get(
  "/selectWithdrawAddress",
  async (req: Request, res: Response, next: NextFunction) => {
    const { coin, uid } = req.query;
    if (process.env.NODE_ENV === "eh") {
      const data = [
        {
          coin: "BTC",
          address: "MHGtdHNwSaQzWaK2N7hxxGmELcZnuRK6fj",
          remark: "sdlkfjlksdfsd",
          id: "abc"
        },
        {
          coin: "BTC",
          address: "MHGtdHNwSaQzWaK2N7hxxGmELcZnuRK6fj",
          remark: "sdlkfjlksdfsd",
          id: "abc"
        },
        {
          coin: "BTC",
          address: "MHGtdHNwSaQzWaK2N7hxxGmELcZnuRK6fj",
          remark: "sdlkfjlksdfsd",
          id: "abc"
        }
      ];
      res.json({
        code: 200,
        data,
        msg: "success"
      });
    }
    try {
      const [num2symbol, symbol2num] = await config.selectSymbolConfig();

      const newurl = `${
        config.api
      }/withdraw/withdrawAddress/${coin}?pageNum=1&pageSize=1000000`;

      const ret = await r(
        {
          method: "GET",
          url: newurl
        },
        req,
        res
      );

      const jsonRet = await selectWithdrawAddress(coin, req, res);

      res.json(jsonRet);
    } catch (e) {
      res.json({
        code: -1,
        data: undefined,
        msg: e
      });
    }
  }
);

router.post(
  "/addAddress",
  async (req: Request, res: Response, next: NextFunction) => {
    const { coin, remark, address, uid } = req.body;

    if (process.env.NODE_ENV === "eh") {
      res.json({
        code: 200,
        data: undefined,
        msg: "success"
      });
    }

    try {
      const newurl = `${config.api}/withdraw/newWithdrawAddress`;

      const [num2symbol, symbol2num] = await config.selectSymbolConfig();

      const ret = await r(
        {
          method: "POST",
          url: newurl,
          body: JSON.stringify({
            address: address,
            coinId: symbol2num[coin],
            remark: remark
          })
        },
        req,
        res
      );

      const jsonRet = JSON.parse(ret.body);

      res.json(jsonRet);
    } catch (e) {
      res.json({
        code: -1,
        data: undefined,
        msg: e
      });
    }
  }
);

router.post(
  "/charge",
  async (req: Request, res: Response, next: NextFunction) => {
    const { coin, remark, address, uid, amount } = req.body;

    if (process.env.NODE_ENV === "eh") {
      res.json({
        code: 200,
        data: undefined,
        msg: "success"
      });
    }

    try {
      const newurl = `${
        config.api
      }/test/testCharge?coinName=${coin}&amount=${amount}&userId=${uid}`;

      const ret = await r(
        {
          method: "POST",
          url: newurl
        },
        req,
        res
      );

      const jsonRet = JSON.parse(ret.body);

      res.json(jsonRet);
    } catch (e) {
      res.json({
        code: -1,
        data: undefined,
        msg: e
      });
    }
  }
);

router.post(
  "/delAddress",
  async (req: Request, res: Response, next: NextFunction) => {
    const { id } = req.body;
    if (process.env.NODE_ENV === "eh") {
      res.json({
        code: 200,
        data: undefined,
        msg: "success"
      });
    }
    try {
      const newurl = `${config.api}/withdraw/withdrawAddress/delete/${id}`;

      const ret = await r(
        {
          url: newurl
        },
        req,
        res
      );

      const jsonRet = JSON.parse(ret.body);
      res.json(jsonRet);
    } catch (e) {
      res.json({
        code: -1,
        data: undefined,
        msg: e
      });
    }
  }
);

router.post(
  "/withdraw",
  async (req: Request, res: Response, next: NextFunction) => {
    const { address, amount, coin, uid } = req.body;
    if (process.env.NODE_ENV === "eh") {
      const newurl = "http://api.zqd.com/user/login";
      res.json({
        code: 200,
        data: undefined,
        msg: "success"
      });
    }
    try {
      const newurl = `${config.api}/withdraw/request`;

      const [num2symbol, symbol2num] = await config.selectSymbolConfig();

      const jsonRetWithdrawAddressMap = await selectWithdrawAddressMap(
        coin,
        req,
        res
      );

      const ret = await r(
        {
          url: newurl,
          body: JSON.stringify({
            addressId: jsonRetWithdrawAddressMap[address].id,
            amount: Number(amount),
            coinId: symbol2num[coin],
            userId: uid
          })
        },
        req,
        res
      );

      const jsonRet = JSON.parse(ret.body);
      res.json(jsonRet);
    } catch (e) {
      res.json({
        code: -1,
        data: undefined,
        msg: e
      });
    }
  }
);

export default router;
